const Code = require("./../../lib/wxa/code.class");
const context = require("./../../context");

module.exports = {
    async addWxaPlugin(wxa_id, name, pluginAppid) {
        const code = new Code(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );
        // 获取小程序信息，刷新accessToken
        let wxa = await doodoo
            .model("wxa")
            .query(qb => {
                qb.where("id", wxa_id);
            })
            .fetch();
        wxa = await context.checkWxaAuthorizerAccessToken(wxa);

        const result = await code.wxa_plugin(
            wxa.authorizer_access_token,
            "apply",
            pluginAppid
        );
        console.log("添加插件结果", result);
        if (result.errmsg === "ok") {
            console.log("添加插件成功");

            await doodoo
                .model("wxaplugins")
                .forge({ wxa_id: wxa_id, name: name, appid: pluginAppid })
                .save();
        } else {
            console.log("添加插件失败");
        }
    }
};
